package com.yashi.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.yashi.dao.TbGroupMapper;
import com.yashi.dao.TbUserMapper;
import com.yashi.dao.UserGroupMapper;
import com.yashi.entity.TbGroup;
import com.yashi.entity.TbUser;
import com.yashi.entity.UserGroup;
import com.yashi.service.GroupService;
import com.yashi.utils.YSUtils;

@Service
public class GroupServiceImpl implements GroupService {
	@Autowired
	private TbGroupMapper groupDao;
	@Autowired
	private TbUserMapper userDao;
	@Autowired
    private UserGroupMapper userGroupDao;
	@Override
	public TbGroup getGroupByid(String id) {
		TbGroup group = groupDao.selectByPrimaryKey(id);
		return group;
	}

	@Override
	public List<TbGroup> getGroupByName(String name) {
		List<TbGroup> groupList = groupDao.getGroupByName(name);
		return groupList;
	}

	@Override
	public List<TbGroup> getAllGroup() {
		List<TbGroup> allGroup = groupDao.getAllGroup();
		return allGroup;
	}
	
	@Override
	public List<TbGroup> selectGroupByUserId(HttpSession session) {
		TbUser user = (TbUser) session.getAttribute("user");
		List<TbGroup> groupList = groupDao.selectGroupByUserId(user.getId());
		return groupList;
	}

	@Override
	public List<TbUser> selectUserbyGroupId(String groupId) {
		List<TbUser> userList = userDao.selectUserbyGroupId(groupId);
		return userList;
	}

	@Override
	public Integer updateById(TbGroup group,HttpSession session) throws Exception {
		TbUser user = (TbUser) session.getAttribute("user");
		group.setUpdateBy(user.getId());
		group.setUpdateDate(YSUtils.getCurrentTime());
		/*if(!group.getUserId().equals(user.getId())) {
			throw new Exception("只有群主才可以修改");
		}*/
		if("".equals(group.getGroupName()) ||group.getGroupName()==null) {
			throw new Exception("群名称为空");
		}
		if (getGroupByName(group.getGroupName()).size()>0) {
			throw new Exception("群名称已存在");
		}
		Integer success = groupDao.updateByPrimaryKeySelective(group);
		return success;
	}

	@Override
	public Integer deleteById(TbGroup group,HttpSession session) throws Exception {
		TbUser user = (TbUser) session.getAttribute("user");
		/*if(!group.getUserId().equals(user.getId())) {
			throw new Exception("只有群主才可以删除");
		}*/
		group.setUpdateBy(user.getUsername());
		group.setUpdateDate(YSUtils.getCurrentTime());
		group.setDelFlag("1");
		Integer success = groupDao.updateByPrimaryKeySelective(group);
		return success;
	}

	@Override
	public Integer addGroup(HttpServletRequest req,TbGroup group,List<String> userLsit,HttpSession session) throws Exception {
		TbUser user = (TbUser) session.getAttribute("user");
		group.setUserId(user.getId());
		group.setCreateBy(user.getUsername());
		group.setId(YSUtils.getUUID());
		group.setCreateDate(YSUtils.getCurrentTime());
		String path1 = req.getContextPath();
        String basePath = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+path1+"/groupPhoto/";
		group.setPhoto(basePath+"20180925163952默认群头像.png");
		group.setDelFlag("0");
		if("".equals(group.getGroupName())||group.getGroupName()==null) {
			throw new Exception("群名称为空");
		}
		List<TbGroup> groupByName = getGroupByName(group.getGroupName());
		if (groupByName.size()>0) {
			throw new Exception("群名称已存在");
		}
		Integer result = groupDao.insertSelective(group);
		
		//将当前用户加入新创建的群中
		userLsit.add(user.getId());
		Integer count = addUserToGroup(group.getId(),userLsit);
		System.out.println("成功添加"+count+"位用户");
		return result;
	}

	@Override
	public Integer addUserToGroup(String groupId, List<String> userIdList) {
		Integer n=0;
		UserGroup userGroup = new UserGroup();
		List<TbUser> userList = userDao.selectUserbyGroupId(groupId);//根据群id查询群成员
		for (String userid : userIdList) {//遍历添加
			boolean result=true;//用来判断群中是否已有这个用户
			userGroup.setId(YSUtils.getUUID());
			userGroup.setUserId(userid);
			userGroup.setGroupId(groupId);
			for (TbUser user : userList) {
				if(user.getId().equals(userid)) {//如果当前群成员中有这个用户
					result=false;
				}
				//TODO
			}
			if(result) {
				userGroupDao.insert(userGroup);
				n++;
			}
		}
		return n;
	}

	@Override
	public Integer deleteUserToGroup(String groupId, List<String> userIdList) {
		Integer n=0;
		for (String userid : userIdList) {
			userGroupDao.deleteByUserIdAndGroupId(userid, groupId);
			n++;
		}
		return n;
	}

	@Override
	public List<TbGroup> finGroupChatList(HttpSession session) {
		TbUser user = (TbUser) session.getAttribute("user");
		List<TbGroup> groupList = groupDao.finGroupChatList(user.getId());
		return groupList;
	}
	
	@Override
	public List<TbGroup> groupPhotoUpload(HttpServletRequest request, TbGroup tbGroup) {
		
		 List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file");
	        
	        if(files.isEmpty()){
	        	System.out.println("文件为空");
	            return null;
	        }
	        
	        String path1 = request.getContextPath();
	        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path1+"/groupPhoto/";
	        String filePath = request.getSession().getServletContext().getRealPath("groupPhoto/");
	        
	        String path = filePath ;
	        List<TbGroup> userChatList =new  ArrayList<TbGroup>();
	        for(MultipartFile file:files){
	            String fileName = file.getOriginalFilename();
	            //获取文件后缀名
//	            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
	            //放入前台展示url
	            tbGroup.setPhoto(basePath+YSUtils.getFileCurrentTime()+fileName);
	            int size = (int) file.getSize();
	            System.out.println(fileName + "-->" + size);
	            //为防止文件被覆盖设置服务器文件名为聊天记录id
	            fileName = YSUtils.getFileCurrentTime()+fileName;
	            //保存文件上传记录
	            groupDao.updateByPrimaryKeySelective(tbGroup);
	            userChatList.add(tbGroup);
	            if(file.isEmpty()){
	                return null;
	            }else{        
	                File dest = new File(path + "/" + fileName);
	                if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
	                    dest.getParentFile().mkdir();
	                }
	                try {
	                    file.transferTo(dest);
	                }catch (Exception e) {
	                    e.printStackTrace();
	                    return null;
	                } 
	            }
	        }
	        return userChatList;
	}

}
